package com.cpx.controller;

import com.cpx.dto.GoodsDto;
import com.cpx.dto.PageBeanDto;
import com.cpx.feign.GoodsFeign;
import com.cpx.po.Goods;
import com.cpx.po.GoodsBrand;
import com.cpx.po.GoodsCategory;
import com.cpx.po.GoodsSupplier;
import com.cpx.vo.JsonResultVo;
import feign.Response;
import io.swagger.annotations.Api;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;


/**
 * @Auther: PanBin
 * @Date: 2018-11-13 17:11
 * @Description: 商品的controller
 * @Version: 1.0
 */
@Api(value = "GoodsController",tags = "商品管理")
@Controller
@RequestMapping("/goods")
public class GoodsController {

    private static Logger logger = LogManager.getLogger(GoodsController.class);
    @Autowired
    private GoodsFeign goodsFeign;


    /**
     * @Author: PanBin
     * @Description:
     * @CreateDate: 跳转到商品列表 17:28
     * @Param []
     * @Return java.lang.String
     */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public String list() {

        return "goods/list";
    }

    /**
     * @Author: PanBin
     * @Description: 保存商品
     * @CreateDate: 2018-11-23 16:43
     * @Param [goods]
     * @Return com.cpx.vo.JsonResultVo
     */
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public @ResponseBody JsonResultVo addGoods(Goods goods) {
        JsonResultVo resultVo = new JsonResultVo();
        try {
            goods.setCreateDate(new Date());
            goodsFeign.insertSelective(goods);
        } catch (Exception e) {
            resultVo.setErrMsg("保存商品失败，请稍后再试");
            logger.error("保存商品失败：",e);
            e.printStackTrace();
        }
        return resultVo;
    }

    @RequestMapping(value = "/getList",method = RequestMethod.POST)
    public @ResponseBody JsonResultVo getList(Integer pageSize,Integer pageNum,Integer goodsCode,String goodsName) {
        JsonResultVo resultVo = new JsonResultVo();
        try {
            List<GoodsDto> goodsDtoList = new ArrayList<>();
            int totalRow = 1000;
            for(int i = 0; i < totalRow; i ++ ) {
                GoodsDto goodsDto = new GoodsDto();
                goodsDto.setId(i);
                goodsDto.setUpdateDate(new Date());
                goodsDtoList.add(goodsDto);
            }
            Iterator<GoodsDto> iterator = goodsDtoList.iterator();
            while (iterator.hasNext()) {
                GoodsDto goodsDto = iterator.next();
                Integer id = goodsDto.getId();
                if (goodsCode != null && !id.toString().contains(goodsCode.toString())) {
                    iterator.remove();
                }
            }
            int start = 0;
            int end = 0;
            double totalPage = Math.ceil((double) goodsDtoList.size() / pageSize);
            for (int i = 1; i <= totalPage; i ++) {
                if (pageNum.intValue() == i) {
                    start = (pageNum - 1) * pageSize;
                    end = start + pageSize;
                    int moEr = goodsDtoList.size() % pageSize;
                    if (i == totalPage && moEr != 0) {
                        end = start + moEr ;
                    }
                    break;
                }
            }
            PageBeanDto<GoodsDto> pageBeanDto = new PageBeanDto<>();
            pageBeanDto.setPageNum(pageNum);
            pageBeanDto.setTotalRow((long)goodsDtoList.size());
            pageBeanDto.setPageList(goodsDtoList.subList(start,end));
            resultVo.setData(pageBeanDto);
        } catch (Exception e) {
            resultVo.setErrMsg("列表获取失败，请稍后再试");
            logger.error("获取商品列表失败，请稍后再试",e);
            e.printStackTrace();
        }
        return resultVo;
    }

    /**
     * @Author: PanBin
     * @Description: 跳转到商品分类页面
     * @CreateDate: 2018-11-21 14:46
     * @Param []
     * @Return java.lang.String
     */
    @RequestMapping(value = "/category",method = RequestMethod.GET)
    public String category() {

        return "goods/category";
    }


    /**
     * @Author: PanBin
     * @Description: 获取商品分类的树
     * @CreateDate: 2018-11-22 17:53
     * @Param [goodsCategory]
     * @Return com.cpx.vo.JsonResultVo
     */
    @RequestMapping(value = "/getCategoryTree",method = RequestMethod.POST)
    public @ResponseBody JsonResultVo getCategoryTree(GoodsCategory goodsCategory) {
        JsonResultVo resultVo = new JsonResultVo();
        try {
            List<GoodsCategory> goodsCategoryList = goodsFeign.getCategoryTree(goodsCategory);
            resultVo.setData(goodsCategoryList);
        } catch (Exception e) {
            logger.error("获取商品分类树失败:",e);
            resultVo.setErrMsg("获取商品分类树失败，请稍后再试");
            e.printStackTrace();
        }
        return resultVo;
    }

    /**
     * @Author: PanBin
     * @Description: 更新商品分类的节点（新增 -->1，编辑 -->2，删除 -->3）
     * @CreateDate: 2018-11-23 10:11
     * @Param [goodsCategory]
     * @Return com.cpx.vo.JsonResultVo
     */
    @RequestMapping(value = "/updateCategoryNode",method = RequestMethod.POST)
    public @ResponseBody JsonResultVo updateCategoryNode(GoodsCategory goodsCategory,Integer type) {
        JsonResultVo resultVo = new JsonResultVo();
        try {
            resultVo.setData(goodsFeign.updateCategoryNode(goodsCategory, type));
        } catch (Exception e) {
            logger.error("编辑商品分类节点失败：",e);
            resultVo.setErrMsg("分配分类失败，请稍后再试");
            e.printStackTrace();
        }
        return resultVo;
    }

    /**
     * @Author: PanBin
     * @Description: 跳转到商品品牌列表
     * @CreateDate: 2018-11-27 9:45
     * @Param []
     * @Return java.lang.String
     */
    @RequestMapping(value = "/brand")
    public String brand() {

        return "goods/brand";
    }

    /**
     * @Author: PanBin
     * @Description: 获取供应商列表
     * @CreateDate: 2018-11-27 10:03
     * @Param [goodsBrand]
     * @Return com.cpx.vo.JsonResultVo
     */
    @RequestMapping(value = "/getBrandList",method = RequestMethod.POST)
    public @ResponseBody JsonResultVo getBrandList(GoodsBrand goodsBrand,Integer pageSize,Integer pageNum) {
        JsonResultVo resultVo = new JsonResultVo();
        try {
            PageBeanDto<GoodsBrand> pageBeanDto = goodsFeign.selectBrandPage(goodsBrand,pageSize,pageNum);
            resultVo.setData(pageBeanDto);
        } catch (Exception e) {
            resultVo.setErrMsg("查询失败，请稍后再试");
            logger.error("供应商查询失败：",e);
            e.printStackTrace();
        }
        return  resultVo;
    }

    /**
     * @Author: PanBin
     * @Description: 添加品牌
     * @CreateDate: 2018-11-27 10:39
     * @Param [goodsBrand]
     * @Return com.cpx.vo.JsonResultVo
     */
    @RequestMapping(value = "/addBrand",method = RequestMethod.POST)
    public @ResponseBody JsonResultVo addBrand(GoodsBrand goodsBrand) {
        JsonResultVo resultVo = new JsonResultVo();
        try {
            goodsFeign.addBrand(goodsBrand);
        } catch (Exception e) {
            resultVo.setErrMsg("新增失败，请稍后再试");
            logger.error("品牌新增失败：",e);
            e.printStackTrace();
        }
        return resultVo;
    }


    /**
     * @Author: PanBin
     * @Description: 删除品牌
     * @CreateDate: 2018-11-27 15:48
     * @Param [brandIds]
     * @Return com.cpx.vo.JsonResultVo
     */
    @RequestMapping(value = "/delBrand",method = RequestMethod.POST)
    public @ResponseBody JsonResultVo delBrand(@RequestParam(value = "brandIdList[]") Integer[] brandIds) {
        JsonResultVo resultVo = new JsonResultVo();
        try {
            goodsFeign.delBrand(brandIds);
        } catch (Exception e) {
            resultVo.setErrMsg("删除失败，请稍后再试");
            logger.error("品牌删除失败：",e);
            e.printStackTrace();
        }
        return resultVo;
    }

    /**
     * @Author: PanBin
     * @Description: 编辑品牌
     * @CreateDate: 2018-11-27 15:51
     * @Param [goodsBrand]
     * @Return com.cpx.vo.JsonResultVo
     */
    @RequestMapping(value = "/editBrand",method = RequestMethod.POST)
    public @ResponseBody JsonResultVo editBrand(GoodsBrand goodsBrand) {
        JsonResultVo resultVo = new JsonResultVo();
        try {
            goodsFeign.editBrand(goodsBrand);
        } catch (Exception e) {
            resultVo.setErrMsg("编辑失败，请稍后再试");
            logger.error("品牌编辑失败：",e);
            e.printStackTrace();
        }
        return resultVo;
    }

    /**
     * @Author: PanBin
     * @Description: 导出品牌列表
     * @CreateDate: 2018-11-29 10:19
     * @Param [goodsBrand]
     * @Return org.springframework.http.ResponseEntity<byte[]>
     */
    @RequestMapping(value = "/exportBrand",method = RequestMethod.POST)
    public void exportBrand(GoodsBrand goodsBrand, HttpServletResponse response) {
        InputStream is = null;
        BufferedInputStream bins = null;
        OutputStream os = null;
        BufferedOutputStream bouts = null;
        try {
            //feign文件下载
            Response feignResponse = goodsFeign.exportBrand(goodsBrand);
            Response.Body body = feignResponse.body();
            is = body.asInputStream();
            bins = new BufferedInputStream(is);     //放到缓冲流里面
            Cookie cookie = new Cookie("expPercent","100");//不可放在最后
            cookie.setPath("/");
            cookie.setMaxAge(300);
            response.addCookie(cookie);
            os = response.getOutputStream();        //获取文件输出IO流
            bouts = new BufferedOutputStream(os);   //输出缓存
            response.setContentType("application/x-download");  //设置response内容的类型
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("品牌.xls", "UTF-8"));// 设置头部信息
            byte[] buffer = new byte[1024];
            /*long totalLen = is.available();         //总文件大小
            int totalRead = 0;      //当前总的输出流
            double percent= 0.00;   //下载进度*/
            int read = 0;//每次的输出量
            while ((read = bins.read(buffer)) != -1) {
               /* totalRead += read;
                percent = new BigDecimal(totalRead).divide(new BigDecimal(totalLen),4,BigDecimal.ROUND_UP).multiply(new BigDecimal(100)).doubleValue();
                logger.info("流读取量：:" + totalRead);
                logger.info("下载进度:" + percent);*/
                bouts.write(buffer, 0, read);
            }
            bouts.flush();
        } catch (Exception e) {
            logger.error("品牌列表导出失败：",e);
            e.printStackTrace();
        } finally {
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bins != null) {
                try {
                    bins.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bouts != null) {
                try {
                    bouts.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * @Author: PanBin
     * @Description: 跳转到供应商列表
     * @CreateDate: 2018-11-30 9:17
     * @Param []
     * @Return java.lang.String
     */
    @RequestMapping(value = "/supplier",method = RequestMethod.GET)
    public String supplier() {

        return "goods/supplier";
    }

    /**
     * @Author: PanBin
     * @Description: 获取供应商列表
     * @CreateDate: 2018-11-30 10:05
     * @Param [goodsSupplier, pageSize, pageNum]
     * @Return com.cpx.vo.JsonResultVo
     */
    @RequestMapping(value = "/getSupplierList",method = RequestMethod.POST)
    public @ResponseBody JsonResultVo getSupplierList(GoodsSupplier goodsSupplier, Integer pageSize, Integer pageNum) {
        JsonResultVo resultVo = new JsonResultVo();
        try {
            PageBeanDto<GoodsSupplier> pageBeanDto = goodsFeign.selectSupplierPage(goodsSupplier,pageSize,pageNum);
            resultVo.setData(pageBeanDto);
        } catch (Exception e) {
            resultVo.setErrMsg("查询失败，请稍后再试");
            logger.error("供应商查询失败：",e);
            e.printStackTrace();
        }
        return  resultVo;
    }

    /**
     * @Author: PanBin
     * @Description: 添加品牌
     * @CreateDate: 2018-11-27 10:39
     * @Param [goodsBrand]
     * @Return com.cpx.vo.JsonResultVo
     */
    /**
     * @Author: PanBin
     * @Description: 添加供应商
     * @CreateDate: 2018-11-30 10:57
     * @Param [goodsBrand]
     * @Return com.cpx.vo.JsonResultVo
     */
    @RequestMapping(value = "/addSupplier",method = RequestMethod.POST)
    public @ResponseBody JsonResultVo addSupplier(GoodsSupplier goodsSupplier) {
        JsonResultVo resultVo = new JsonResultVo();
        try {
            goodsFeign.addSupplier(goodsSupplier);
        } catch (Exception e) {
            resultVo.setErrMsg("新增失败，请稍后再试");
            logger.error("供应商新增失败：",e);
            e.printStackTrace();
        }
        return resultVo;
    }

    /**
     * @Author: PanBin
     * @Description: 编辑供应商
     * @CreateDate: 2018-11-30 11:18
     * @Param [goodsSupplier]
     * @Return com.cpx.vo.JsonResultVo
     */
    @RequestMapping(value = "/editSupplier",method = RequestMethod.POST)
    public @ResponseBody JsonResultVo editSupplier(GoodsSupplier goodsSupplier) {
        JsonResultVo resultVo = new JsonResultVo();
        try {
            goodsFeign.editSupplier(goodsSupplier);
        } catch (Exception e) {
            resultVo.setErrMsg("编辑失败，请稍后再试");
            logger.error("供应商编辑失败：",e);
            e.printStackTrace();
        }
        return resultVo;
    }


   /**
    * @Author: PanBin
    * @Description: 删除供应商
    * @CreateDate: 2018-11-30 13:41
    * @Param [supplierIds]
    * @Return com.cpx.vo.JsonResultVo
    */
    @RequestMapping(value = "/delSupplier",method = RequestMethod.POST)
    public @ResponseBody JsonResultVo delSupplier(@RequestParam(value = "supplierIdList[]") Integer[] supplierIds) {
        JsonResultVo resultVo = new JsonResultVo();
        try {
            goodsFeign.delSupplier(supplierIds);
        } catch (Exception e) {
            resultVo.setErrMsg("删除失败，请稍后再试");
            logger.error("品牌删除失败：",e);
            e.printStackTrace();
        }
        return resultVo;
    }

   /**
    * @Author: PanBin
    * @Description: 导出供应商
    * @CreateDate: 2018-11-30 13:58
    * @Param [goodsBrand, response]
    * @Return void
    */
    @RequestMapping(value = "/exportSupplier",method = RequestMethod.POST)
    public void exportSupplier(GoodsSupplier goodsSupplier, HttpServletResponse response) {
        InputStream is = null;
        BufferedInputStream bins = null;
        OutputStream os = null;
        BufferedOutputStream bouts = null;
        try {
            //feign文件下载
            Response feignResponse = goodsFeign.exportSupplier(goodsSupplier);
            Response.Body body = feignResponse.body();
            is = body.asInputStream();
            bins = new BufferedInputStream(is);     //放到缓冲流里面
            Cookie cookie = new Cookie("expPercent","100");//不可放在最后
            cookie.setPath("/");
            cookie.setMaxAge(300);
            response.addCookie(cookie);
            os = response.getOutputStream();        //获取文件输出IO流
            bouts = new BufferedOutputStream(os);   //输出缓存
            response.setContentType("application/x-download");  //设置response内容的类型
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("供应商.xls", "UTF-8"));// 设置头部信息
            byte[] buffer = new byte[1024];
            /*long totalLen = is.available();         //总文件大小
            int totalRead = 0;      //当前总的输出流
            double percent= 0.00;   //下载进度*/
            int read = 0;//每次的输出量
            while ((read = bins.read(buffer)) != -1) {
               /* totalRead += read;
                percent = new BigDecimal(totalRead).divide(new BigDecimal(totalLen),4,BigDecimal.ROUND_UP).multiply(new BigDecimal(100)).doubleValue();
                logger.info("流读取量：:" + totalRead);
                logger.info("下载进度:" + percent);*/
                bouts.write(buffer, 0, read);
            }
            bouts.flush();
        } catch (Exception e) {
            logger.error("供应商列表导出失败：",e);
            e.printStackTrace();
        } finally {
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bins != null) {
                try {
                    bins.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bouts != null) {
                try {
                    bouts.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

